package cn.abdl.springsecurity.service;

import cn.abdl.springsecurity.dao.SysUserDao;
import cn.abdl.springsecurity.entity.dto.SysUser;
import cn.abdl.springsecurity.entity.dto.SysUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
public class CustomUserDetailService implements UserDetailsService {
    @Autowired
    private SysUserDao sysUserDao;
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Optional<SysUserDto> userDto = sysUserDao.findByUsername(name);
        if (userDto.isEmpty()){
            throw new BadCredentialsException("用户名或密码错误");
        }
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
        SysUser user = new SysUser();
        user.setAreaId(userDto.get().getAreaId());
        user.setUsername(userDto.get().getUsername());
        user.setNickname(userDto.get().getNickname());
        user.setPassword(userDto.get().getPassword());
        user.setState(userDto.get().getState());
        user.setAuthorities(auths);
        //从查询数据库返回users对象，得到用户名和密码，返回
        return user;
    }
}
